// pages/goods/goods.js
//获取应用实例
const app = getApp();
const api = require('../../utils/api');
const constant = require('../../utils/constant');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    BASEURLWWW:constant.BASEURLWWW,
    // 商品详情
    goodsDetail: {
      recommend: ''
    },
    // 数量
    num: 1,
    // 运费弹窗show
    freightShow:false,
    // 商品sku：key_name,price
    goods_spec: {},
    // 商品评论列表
    goodsEvaluateData:[],
    // 商品评论列表分页
    goodsEvaluatePagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    // 为你推荐数据
    guessDataList: [],
    // 为你推荐分页
    pagination:{
      pageNum: 1,  //分页初始值，页号1
      pageSize: 10, //分页初始值，每页20条
      total: null
    },
    screen:{
      is_recommend:1
    },
    // 返回顶部
    floorstatus: false,
    // 分享弹窗
    isShareShow: false,
    // 海报弹窗
    isPostersPopupShow: false,
    // 关闭和保存按钮
    isCloseAndSaveImgShow: false,
    // 二维码
    codeImg: '',
    // canvas图片
    canvas: '',
    // canvas单位
    rpx: 0,
    // 画布参数(保存图片按钮：50，保存图片上边距：10，上下边距：40，画布上下/左右内间距：20,二维码宽/高：画布宽的1/3，长按查看：26，保存提示：26)
    canvasOptions:{
      pixelRatio: 0,
      windowWidth: 0,
      windowHeight: 0,
    },
    // canva图片容器适配宽高
    coverWrap:{
      width:0,
      height:0
    },
    // 购物车列表数据
    carNum: 0,
    getPhoneNumber: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取手机号
    this.setData({
      getPhoneNumber: this.selectComponent("#getPhoneNumber")
    })
    let that = this;
    let goods_id = null;
    if(options.scene){
      goods_id = decodeURIComponent(options.scene);
    }
    if(options.goods_id){
      goods_id = options.goods_id
    }
    // 获取商品详情
    this.getGoodsDetailData(goods_id);
    // 获取评论列表(10条)
    this.getGoodsEvaluateData(goods_id,this.data.goodsEvaluatePagination);
    // 为你推荐列表
    this.getGuessListRandData(this.data.screen,this.data.pagination);

    let navigationHeight = this.data.navigationHeight;
    
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          'canvasOptions.pixelRatio': res.pixelRatio,
          'canvasOptions.windowWidth': res.windowWidth,
          'canvasOptions.windowHeight': res.windowHeight,
          'canvasOptions.contentWidth': res.windowWidth-20,
          'canvasOptions.contentHeight': res.windowHeight-20,
        })
      },
    })

    // 获取购物车列表数据
    this.getCarListData();
  },
  // 获取购物车列表数据
  getCarListData:function(){
    api.carList([]).then(res => {
      if(res.code == 0){
        this.setData({
          carNum: res.data.data.length
        })
      }
    })
  },
  // 获取为你推荐列表
  getGuessListRandData:function(screen,pagination){
    let guessDataListArr = this.data.guessDataList;
    // 数据已经到底
    if( guessDataListArr.length == this.data.pagination.total){
      wx.showToast({
        title: '没有更多了~',
        icon: 'none',
        duration: 1500
      })
    }else{
      api.getGuessListRandData(screen,pagination).then(res => {
        if(res.code == 0){
          if(res.data.total != 0){
            guessDataListArr.push(...res.data.list);
            this.setData({
              guessDataList: guessDataListArr,
              'pagination.total': res.data.total
            })
          }
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          })
        }
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let newPageNum = this.data.pagination.pageNum + 1;
    this.setData({
      'pagination.pageNum': newPageNum
    })
    this.getGuessListRandData(this.data.screen,this.data.pagination);
  },
  /**
   * 获取滚动条当前位置
   */
  onPageScroll: function (e) {
    if (e.scrollTop > 500) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    this.setData({
      isShareShow: false
    })
    return {
      title: this.data.goodsDetail.name,
      path: `/pages/goods/goods?goods_id=${this.data.goodsDetail.goods_id}`
    }
  },
  /**
   * 分享到朋友圈
   */
  onShareTimeline: function(res){
    let goodsDetail = this.data.goodsDetail;
    let img = goodsDetail.goods_pic[0].url_x800 != '' ? goodsDetail.goods_pic[0].url_x800 : goodsDetail.goods_pic[0].url; //取得是每个店铺的图和店铺名称
    return {
      title: goodsDetail.name, //字符串  自定义标题
      query: `goods_id=${goodsDetail.goods_id}`,  //页面携带参数
      imageUrl:img   //图片地址
    }
  },
  // 返回上一级
  back:function(){
    let pages = getCurrentPages(); //页面对象
    let prevpage = pages[pages.length - 2]; //上一个页面对象
    // if(prevpage){
    //   wx.reLaunch({
    //     url: `/${prevpage.route}`,
    //   })
    // }else{
    //   wx.reLaunch({
    //     url: '/pages/index/index',
    //   })
    // }
    if(wx.getStorageSync("goodsDetailPath")){ // 直接购买页面返回后跳转到上一页
      wx.reLaunch({
        url: '/' + wx.getStorageSync("goodsDetailPath"),
        success: function(e){
          wx.removeStorageSync('goodsDetailPath')
        }
      })
    }else if(prevpage){ // 非直接购买，返回上一页
      // wx.reLaunch({
      //   url: `/${prevpage.route}`,
      // })
      wx.navigateBack({
        delta: 1
      })
    }else{ // 分享没有上一页，直接返回首页
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
  // 跳转到购物车
  jumpToCar:function(){
    api.checkPhoneNumber().then(isPhoneNumber => {
      if(isPhoneNumber){
        wx.switchTab({
          url: '/pages/car/car',
        })
      }else{
        this.data.getPhoneNumber.showDialog();
      }
    })
    
  },
  // 跳转到首页
  jumpToIndex:function(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 跳转到评价列表
  jumpToGoodsEvaluate:function(e){
    if(e.currentTarget.dataset.goodsid){
      wx.navigateTo({
        url: '/pages/goodsEvaluate/goodsEvaluate?goods_id=' + e.currentTarget.dataset.goodsid
      })
    }
  },
  // 商品切换
  showGoods:function(e){
    let nowGoodsId = this.data.goodsDetail.goods_id;
    let targetGoodsId = e.currentTarget.dataset.id;
    if(targetGoodsId != nowGoodsId){
      this.getGoodsDetailData(targetGoodsId);
      this.getGoodsEvaluateData(targetGoodsId,this.data.goodsEvaluatePagination);
    }
  },
  // 获取商品详情数据
  getGoodsDetailData:function(goods_id){
    api.getGoodsDetail(goods_id).then(res => {
      if(res.code == 0){
          // 解构商品sku
          let goodsSpecSkuIdArr = [];
          res.data.goods_spec.forEach(item => {
            let splitArr = item.key_name.split("_");
            splitArr.forEach((node,index) => {
              splitArr[index] = parseInt(node);
            })
            goodsSpecSkuIdArr.push(splitArr);
          })
          // 给商品规格组添加show字段、规格项添加choose字段
          res.data.specconfig.config_data.forEach(item => {
            let selectedArr = [];
            item.spec_item.forEach(node => {
              // 存放已选规格项id
              if(node.selected){
                selectedArr.push(node.spec_item_id);
              }
              // 让第一组sku数据规格项默认显示
              if(goodsSpecSkuIdArr.length > 0){
                if(goodsSpecSkuIdArr[0].indexOf(node.spec_item_id) != -1){
                  node.choose = true;
                }else{
                  node.choose = false;
                }
              }
              
            })
            // 规格项空则不显示整个规格组
            if(selectedArr.length > 0){
              item.show = true;
            }else{
              item.show = false;
            }
          })
          // 给商品详情富文本内容加样式
          if(res.data.m_content){
            res.data.m_content = res.data.m_content.replace(/\<img/gi, '<img class="goodsContentImg"');
          }
          this.setPrice(res.data,goodsSpecSkuIdArr[0]);
        
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  // sku重组并返回sku价格
  setPrice:function(goodsDetail,idArr){
    let key_name = '';
    if(idArr && idArr.length > 0){ // 有规格项
      idArr.forEach((item,index) => {
        index += 1;
        if(index < idArr.length){
          key_name += item.toString() + '_';
        }else{
          key_name += item.toString();
        }
      })
      goodsDetail.goods_spec.forEach(item => {
        if(item.key_name == key_name){
          this.setData({
            goodsDetail,
            goods_spec:item
          })
        }
      })
    }else{
      this.setData({
        goodsDetail,
        // 根据规格设置价格
        'goods_spec.price':goodsDetail.shop_price,
        'goods_spec.market_price':goodsDetail.market_price,
        'goods_spec.goods_id':goodsDetail.goods_id,
        'goods_spec.store_qty':goodsDetail.store_qty,
      })
    }
  },
  // 规格选择
  specChoose:function(e){
    let goodsDetailArr =this.data.goodsDetail;
    let spec_id =  e.currentTarget.dataset.parentid;
    let spec_item_id = e.currentTarget.dataset.id;
    let speSkuChoose = [];
    goodsDetailArr.specconfig.config_data.forEach(item => {
      if(spec_id == item.spec_id){
        item.spec_item.forEach(node => {
          if(spec_item_id == node.spec_item_id){
            node.choose = true;
            speSkuChoose.push(node.spec_item_id);
          }else{
            node.choose = false;
          }
        })
      }else{
        item.spec_item.forEach(node => {
          if(node.choose){
            speSkuChoose.push(node.spec_item_id);
          }
        })
      }
    })
    this.setPrice(goodsDetailArr,speSkuChoose);
  },
  // 数量文本框
  numInput: function(e){
    if(e.detail.value == 0){
      this.setData({
        num: 1
      })
    }else{
      this.setData({
        num: e.detail.value
      })
    }
  },
  // 数量文本框+
  plus: function(){
    let num = this.data.num;
    num++
    this.setData({
      num
    })
  },
  // 数量文本框-
  minus: function(){
    let num = this.data.num;
    num--
    if(num == 0){
      num = 1;
    }
    this.setData({
      num
    })
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  // 运费弹窗显示
  freightDailog: function(){
    this.setData({
      freightShow: true
    })
  },
  // 关闭运费弹窗
  closeFreighDailog: function(){
    this.setData({
      freightShow: false
    })
  },
  // 加入购物车或立即购买
  alreadyBuy:function(e){
    api.checkPhoneNumber().then(isPhoneNumber => {
      if(isPhoneNumber){
        let handle = e.currentTarget.dataset.handle;
        let goods_spec = this.data.goods_spec;
        if(this.data.num > this.data.goods_spec.store_qty){
          wx.showToast({
            title: '抱歉，库存不足！',
            icon: 'none',
            duration: 1500
          })
          return;
        }
        if(handle == 'cart'){ // 加入购物车
          let cartGoods = [];
          let goodsObj = {
            goods_id: goods_spec.goods_id,
            goods_spec_id: goods_spec.goods_spec_id?goods_spec.goods_spec_id:0,
            key_name: goods_spec.key_name?goods_spec.key_name:'',
            key_value: goods_spec.key_value?goods_spec.key_value:'',
            price:goods_spec.price,
            goods_num: this.data.num,
          };
          cartGoods.push(goodsObj);
          api.addToCart(cartGoods).then(res => {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            })
            this.getCarListData();
          })
        }else{ // 立即购买
          // 获取上一页路由
          let pages = getCurrentPages(); //页面对象
          let prevpage = pages[pages.length - 2]; //上一个页面对象
          if(prevpage){
            wx.setStorage({      
              key: 'goodsDetailPath', 
              data: prevpage.route    
            }) 
          }
          let goodsDetail = this.data.goodsDetail;
          let goods = {
            goods_id: goods_spec.goods_id,
            goods_spec_id: goods_spec.goods_spec_id?goods_spec.goods_spec_id:0,
            key_name: goods_spec.key_name?goods_spec.key_name:'',
            key_value: goods_spec.key_value?goods_spec.key_value:'',
            price:goods_spec.price,
            goods_num: this.data.num,
            goods_pic: goodsDetail.goods_pic,
            name: goodsDetail.name
          }

          wx.navigateTo({
            url: `/pages/pay/pay?goods=${JSON.stringify(goods)}`,
          })
        }
      }else{
        console.log(this.data.getPhoneNumber)
        this.data.getPhoneNumber.showDialog();
      }
    })
    
    
  },
  // 获取商品评价数据
  getGoodsEvaluateData:function(goods_id,pagination){
    api.getGoodsEvaluate({goods_id},pagination).then(res => {
      if(res.code == 0){
        this.setData({
          goodsEvaluateData: res.data.data.list
        })
      }
    })
  },
  // 为你推荐跳转到商品详情
  jumpToGoods:function(e){
    let goods_id = e.currentTarget.dataset.goodsid;
    this.setData({
      goodsEvaluateData: [],
      guessDataList: [],
      'pagination.pageNum':1
    })
    // 获取商品详情
    this.getGoodsDetailData(goods_id);
    // 获取评论列表(10条)
    this.getGoodsEvaluateData(goods_id,this.data.goodsEvaluatePagination);
    // 为你推荐列表
    this.getGuessListRandData(this.data.screen,this.data.pagination);
    this.goTop();
  },
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  // 显示分享弹窗
  showSharePopup:function(){
    this.setData({
      isShareShow: true
    })
  },
  // 取消/关闭分享弹窗
  hiddeSharePopup:function(){
    this.setData({
      isShareShow: false
    })
  },
  // 显示海报弹窗/关闭分享弹窗
  drawPosters:function(){
    let that = this;

    this.setData({
      isShareShow: false,
    })
    wx.showLoading({
      title: '海报生成中...',
      icon: 'loading'
    });
    that.createNewImg();
    
  },
  // 取消/关闭海报弹窗
  hiddePostersPopup:function(){
    this.setData({
      isPostersPopupShow: false
    })
  },
  /**
 * 绘制圆角矩形
 * @param {Object} context - canvas组件的绘图上下文
 * @param {Number} x - 矩形的x坐标
 * @param {Number} y - 矩形的y坐标
 * @param {Number} w - 矩形的宽度
 * @param {Number} h - 矩形的高度
 * @param {Number} r - 矩形的圆角半径
 * @param {String} [c = 'transparent'] - 矩形的填充色
 */
  drawRectangle:function(ctx, x, y, w, h, r, c = '#fff'){
    ctx.save();
    // 开始绘制
    ctx.beginPath();
    // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
    // 这里是使用 fill 还是 stroke都可以，二选一即可
    ctx.setFillStyle('transparent')
    // ctx.setStrokeStyle('transparent')
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
 
    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
 
    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
 
    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
 
    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)
    ctx.closePath()
    // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
    ctx.setStrokeStyle(c);
    ctx.setFillStyle(c);
    ctx.fill();
    
    // 剪切
    ctx.stroke();
    
  },
  // 海报文字处理
  fontDraw:function(nodeInfo,context,width){
    let that = this;
    // let str = '有记者提问，美国国务卿布林肯接受采访时谈到香港问题，称美国或会效仿英国，向“逃离镇压”的香港人敞开大门。中方对此有何回应？美国国务卿布林肯接受采访时谈到香港问题!'
    var chr =nodeInfo.split("");//这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    context.setFontSize(14);
    context.setFillStyle("#000");
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < width-20) {
        temp += chr[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp); 
    //如果数组长度大于2 则截取前两个
    if (row.length > 3) {
      var rowCut = row.slice(0, 3);
      var rowPart = rowCut[2];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 220) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."//这里只显示两行，超出的用...表示
      rowCut.splice(2, 2, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 10, that.data.canvasOptions.contentWidth+100+b*18, that.data.canvasOptions.contentWidth);
    }
    context.stroke();
  },
  // 获取二维码
  qrcode_image:function(context,contentWidth){
    let that = this;
    let page = 'pages/goods/goods';
    let scene = that.data.goodsDetail.goods_id;
    let codeWidth = 280;
    let is_hyaline = true;
    api.getCode(page,scene,codeWidth,is_hyaline).then(res => {
      if(res.code == 0){
        // let codeShowWidth = (width/2)-40;
        wx.getImageInfo({
          src: that.data.BASEURLWWW+res.data.data.path,
          success:function (codeImg){
            context.drawImage(codeImg.path, (that.data.canvasOptions.windowWidth-contentWidth/4)/2, contentWidth+158, contentWidth/4, contentWidth/4);
            //长按或扫描查看
            context.setFontSize(14);
            context.setFillStyle('#666');
            context.font = 'normal bold 14px Arial,sans-serif '
            let str = '长按或扫描查看';
            context.fillText(str,  (that.data.canvasOptions.windowWidth - context.measureText(str).width) / 2, contentWidth+170+contentWidth/4);
            context.stroke();
            //保存后，可以从手机相册分享
            context.setFontSize(12);
            context.setFillStyle('#666');
            context.font = 'normal 12px Arial,sans-serif '
            context.setTextAlign('left');
            let strLast = '保存后，可以从手机相册分享';
            context.fillText(strLast, (that.data.canvasOptions.windowWidth - context.measureText(strLast).width) / 2, contentWidth+190+contentWidth/4);
            context.stroke();
            context.draw();
            context.draw(true,setTimeout(()=>{
              wx.canvasToTempFilePath({
                canvasId: 'mycanvas',
                width: that.data.canvasOptions.windowWidth,
                height: that.data.canvasOptions.windowHeight,
                destWidth: that.data.canvasOptions.windowWidth*that.data.canvasOptions.pixelRatio,
                destHeight: that.data.canvasOptions.windowHeight*that.data.canvasOptions.pixelRatio,
                fileType: 'jpg',
                quality: 1,
                success: (res) => {
                  wx.hideLoading();
                  that.setData({
                    isPostersPopupShow: true,
                    canvas: res.tempFilePath
                  })
                  // 获取图片容器宽高
                  wx.createSelectorQuery().selectAll('.main').boundingClientRect(function (rects) {
                    that.setData({
                      'coverWrap.width': (that.data.canvasOptions.windowWidth*rects[0].height)/that.data.canvasOptions.windowHeight,
                      'coverWrap.height':rects[0].height,
                    })
                  }).exec();
                },
              }, that)
            },500));
          }
        })
      }
    })
  },
  // 画海报
  createNewImg:function(){
    let that = this;
    let goodsDetail = this.data.goodsDetail;
    let goodsPic = goodsDetail.goods_pic[0].url_x800 != ''?that.data.BASEURLWWW+goodsDetail.goods_pic[0].url_x800:that.data.BASEURLWWW+goodsDetail.goods_pic[0].url;

    // 获取canvas节点
    let context = wx.createCanvasContext('mycanvas');
    wx.getImageInfo({
      src: goodsPic,
      success: function (img){
        // 背景
        that.drawRectangle(context,0,0,that.data.canvasOptions.windowWidth,that.data.canvasOptions.windowHeight,15,'#fff');
        // 头部背景圆角矩形(36)
        that.drawRectangle(context,10,10,that.data.canvasOptions.contentWidth,26,12,'#f1f1f1');
        //头部文字
        context.setFontSize(12);
        context.setFillStyle('#333');
        let str = '推荐一个好物给你，请查收';
        context.fillText(str, (that.data.canvasOptions.contentWidth - context.measureText(str).width) / 2,26);
        context.stroke();
        // 绘制商品图
        context.drawImage(img.path, 10, 46, that.data.canvasOptions.windowWidth-20, that.data.canvasOptions.windowWidth-20);
        
        //绘制价格符号
        context.setFontSize(14);
        context.setFillStyle('red');
        context.setTextAlign('left');
        context.fillText("￥", 10, that.data.canvasOptions.windowWidth+46,20);
        context.stroke();
        //绘制价格(46)
        context.setFontSize(18);
        context.setFillStyle('red');
        context.setTextAlign('left');
        context.fillText(goodsDetail.shop_price, 25, that.data.canvasOptions.windowWidth+46,that.data.canvasOptions.contentWidth-20);
        context.stroke();
        //价格具有时效性(46+20+10)
        context.setFontSize(12);
        context.setFillStyle('#666');
        context.setTextAlign('left');
        context.fillText("价格具有时效性", 10, that.data.canvasOptions.windowWidth+60,that.data.canvasOptions.contentWidth);
        context.stroke();
        //绘制商品名字(46+20+10+80)
        that.fontDraw(goodsDetail.name,context,that.data.canvasOptions.contentWidth);
        // 绘制二维码
        that.qrcode_image(context,that.data.canvasOptions.contentWidth);
      }
    })
  },
  // 保存图片
  saveImg:function(){
    wx.getSetting({ //询问用户是否保存相册到本地
      success: (set) => {
        wx.saveImageToPhotosAlbum({
          filePath: this.data.canvas,
          success: (res) => {
            if (res.errMsg == "saveImageToPhotosAlbum:ok") {
              wx.showToast({
                title: '保存成功',
              });
              this.setData({
                isPostersPopupShow: false
              })
            }
          }
        })
        //拒绝保存到本地的处理机制
        if (set.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting()
        }
      }
    })
  },
  // 收藏商品
  collection:function(){
    console.log(this.data.goodsDetail)
    let goods_id = this.data.goodsDetail.goods_id;
    let is_collect = this.data.goodsDetail.is_collect;
    if(is_collect == 0){ // 添加收藏
      api.addCollection(goods_id).then(res => {
        if(res.code == 0){
          this.setData({
            'goodsDetail.is_collect': 1
          })
          wx.showToast({
            title: '收藏成功',
            icon: 'none'
          })
        }
      })
    }
    if(is_collect == 1){ // 取消收藏
      api.cancelCollection(goods_id).then(res => {
        if(res.code == 0){
          this.setData({
            'goodsDetail.is_collect': 0
          })
          wx.showToast({
            title: '取消收藏',
            icon: 'none'
          })
        }
      })
    }
    
  }
})